package com.jiufen.Exception;

import com.google.errorprone.annotations.Var;
import com.jiufen.Pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result handleException(Exception e){
        log.error("全局异常处理器，拦截到异常：{}",e);
        return Result.error("Sorry！服务器发生异常,请稍后再试");
    }

    /**
     * 拦截数据库重复异常
     * @param e
     * @return
     */
    @ExceptionHandler
    public Result handleException(DuplicateKeyException e){
        log.error("全局异常处理器，拦截到异常：{}",e);
        String message = e.getMessage();
        int i = message.indexOf("Duplicate entry");
        String errorString = message.substring(i);
        String[] s = errorString.split(" ");
        return Result.error("Sorry！"+s[2]+"数据已存在");

    }
    /**
     * 删除班级前检查是否有学生异常拦截器
     */

    @ExceptionHandler
    public Result handleException(RemainingStudentsException e){
        log.error("全局异常处理器，拦截到异常：{}",e);
        return Result.error(e.getMessage());
    }
}
